const axios = require('axios')
const crypto = require('crypto')

const wechatPay = async (request, reply) => {
  // console.log(request, reply)
  // const url = `https://api.weixin.qq.com/sns/jscode2session?appid=wx42ad5abf8d45edcc&secret=2fca387f4108a082c204f443bcaea880&js_code=0c11cC0w3C4gU33n1L1w30PxdC41cC0c&grant_type=authorization_code`
  // const response = await axios.get(url)
  // console.log(response)
  const data = await getAccessToken(
    'wx42ad5abf8d45edcc',
    '2fca387f4108a082c204f443bcaea880'
  )
  await setAccessToken(
    {
      appid: 'wx42ad5abf8d45edcc',
      mchid: '1699691184',
      description: 'hh',
      out_trade_no: '1217752501201407033233368018',
      notify_url: 'https://www.weixin.qq.com/wxpay/pay.php',
      amount: {
        total: 10,
        currency: 'CNY',
      },
      payer: {
        openid: '0c11cC0w3C4gU33n1L1w30PxdC41cC0c',
      },
    },
    data
  )
  // return reply.code(200).send({
  //   code: reply.statusCode,
  //   message: '保存成功！',
  //   data: null,
  //   error: null,
  // })
}
async function setAccessToken(obj, token) {
  const accessTokenUrl = `https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi`
  const results = await axios.post(accessTokenUrl, obj, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: token, // 替换为有效的访问令牌
      // 其他必要的 HTTP 头
    },
  })
  console.log(results)
}

async function getAccessToken(appId, appSecret) {
  const accessTokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`
  const response = await axios.post(accessTokenUrl)
  const { data } = response
  return data.access_token
}
module.exports = {
  wechatPay,
}
